/*
 * @Author: yangrongxin
 * @Date: 2021-08-18 13:52:34
 * @LastEditors: yangrongxin
 * @LastEditTime: 2021-09-01 15:34:57
 */
import { useReducer, forwardRef, useImperativeHandle } from 'react';
import { View, Text } from '@tarojs/components';
import { AtIcon } from 'taro-ui';
import styles from './index.module.less';

function reduce(state, action) {
  if (action.type === 'update') {
    return {
      ...state,
      ...action.payload,
    };
  }
}

interface IOrderComponentProps {
  extendWapperClass?: string; // 扩展的wapperclassname
  onChange?: any; // 修改sort进行联动的参数
}

const OrderComponent = (props: IOrderComponentProps, ref: any) => {
  const { extendWapperClass, onChange } = props;

  const filterList = [
    {
      name: 'xCreateTime',
      title: '最新',
      asc: true,
    },
    {
      name: 'evaluationNum',
      title: '最热',
      asc: true,
    },
    {
      name: 'price',
      title: '价格',
      asc: true,
    },
  ];

  const [orderState, updateOrderState] = useReducer(reduce, {
    xCreateTime: true,
    evaluationNum: true,
    price: true,
  });

  /* 修改当前的排序参数 */
  const changeSort = (curName, curSort) => {
    onChange &&
      onChange({
        orderBy: curName,
        asc: !curSort,
      });
    updateOrderState({
      type: 'update',
      payload: {
        xCreateTime: true,
        evaluationNum: true,
        price: true,
        [curName]: !curSort,
      },
    });
  };

  useImperativeHandle(ref, () => ({
    resetSort: () => {
      updateOrderState({
        type: 'update',
        payload: {
          xCreateTime: true,
          evaluationNum: true,
          price: true,
        },
      });
    },
  }));

  return (
    <View className={`${styles.container} ${extendWapperClass}`}>
      <View className={styles.wapperContainer}>
        {/* 筛选内容分布 */}
        {filterList.map((item: any) => {
          const { name, title } = item;
          const curSort = orderState[name];
          return (
            <View key={name} className={!curSort ? styles.selected : ''} onClick={() => changeSort(name, curSort)}>
              <Text>{title}</Text>
              <AtIcon prefixClass="icon" value="sorting" size="12" />
            </View>
          );
        })}
      </View>
    </View>
  );
};

export default forwardRef(OrderComponent);
